from main import logger
from socket import gethostbyname
import signal
from threading import Thread
from time import sleep
from urllib2 import urlopen

HOSTNAME_TEST = 'www.google.com'
URL_TEST = 'http://www.google.com'


class HeartBeat(Thread):
    
    def __init__(self, sify_conn, interval):
        Thread.__init__(self)
        self.conn = sify_conn
        self.interval = interval
        self.status = True
       
    def run(self):
        sleep(self.interval)
        while 1:
            try: 
                name = socket.gethostbyname(HOSTNAME_TEST)
                if self.status == False:
                    logger.info("Connection restored")
                    self.status = True
            except Exception, e:
                if self.status == True:
                    logger.info("Connection failed")
                    logger.info("Trying sify connect")
                    if self.conn.login() == '0':
                        self.status = True
                    else:
                        self.status = False
            sleep(self.interval)
